import React, {
	Component
} from 'react'
import {
	connect
} from 'react-redux'
import fetch from 'isomorphic-fetch'

// let state = {
// 	isFetching: fales,
// 	didInvalidate: true,
// 	lastUpdated: '',
// 	article: ''
// }

// action
const receiveData = (json) => {
	return {
		type: "RECEIVE_DATA",
		isFetching: false,
		article: json.content
	}
}

const fetchArticle = () => {
	return (dispatch) => {
		fetch('http://localhost:80/article/once/11', {
			method: 'GET'
		}).then(res => res.json()).then((res) => {
			console.log(res)
			dispatch(receiveData(res))
		})
	}
}

// reducer
export const ft = (state = {
	isFetching: false
}, action) => {
	switch (action.type) {
		case "REQUEST_DATA":
			return Object.assign({}, state, {
				isFetching: true
			})
		case "RECEIVE_DATA":
			return Object.assign({}, state, {
				isFetching: false,
				article: action.article
			})
		default:
			return state
	}
}

// component
class FetchTest extends Component {
	componentDidMount() {
		const {
			dispatch
		} = this.props
		dispatch(fetchArticle())
	}
	handleClick() {
		const {
			dispatch
		} = this.props
		dispatch(fetchArticle())
	}
	render() {
		return (
			<div>
				<p>{this.props.article}</p>
				<button onClick={this.handleClick.bind(this)}>Refresh</button>
			</div>
		)
	}
}

FetchTest.defaultProps = {
	article: 'Loading......'
}

const mapStateToProps = (state) => {
	return {
		article: state.ft.article
	}
}

const mapDispatchToProps = (dispatch) => {
	return {

	}
}

export default connect(mapStateToProps)(FetchTest)